import { message } from "ant-design-vue";
import { UseFetchOptions } from "nuxt/dist/app/composables/fetch";
import { HttpResultInterface } from "~~/types";
import getBaseUrl from "./getBaseUrl";

export async function useMyFetch<T>(
  url: string,
  options?: UseFetchOptions<HttpResultInterface<T>>
): Promise<HttpResultInterface<T | null>> {
  let token = useCookie("token");

  const { data } = await useFetch(url, {
    baseURL: getBaseUrl,
    ...options,
    onRequest({ request, options }) {
      options.headers = (options.headers || {}) as { [key: string]: string };
      options.headers.authorization = token.value
        ? `Bearer ${token.value}`
        : "";
    },
    onResponse({ request, response, options }) {
      if (url == "/login") {
        token.value = response.headers.get("token");
      }
    },
    onResponseError({ request, response, options }) {
      if (url == "/login" && response._data.code == 401) {
        const { push } = useRouter();
        token.value = "";
        push("/error");
      } else {
        message.error(response._data.message);
      }
    },
  });
  let result: HttpResultInterface<T> = {
    code: data.value?.code!,
    message: data.value?.message!,
    data: data.value?.data!,
  };
  if (result.code == "30000") {
    return result;
  } else {
    result.data = null;
    return result;
  }
}
